//
//  RegisterViewController.m
//  JunZeWristband
//
//  Created by Kendama on 2017/8/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterView.h"
#import "WebViewController.h"
#import "PublicRegisterApi.h"
#import "PublicGetRegisterCodeApi.h"

@interface RegisterViewController ()

@property(nonatomic,strong) RegisterView *containerView;

@end

@implementation RegisterViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    
}

- (void)refreshBaseControlValue
{
    
}

#pragma mark - 点击事件
- (void)getVerifyCode
{
    if (![self.containerView.phoneView.phoneTextField.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请输入正确的手机号码...")];
        return;
    }
    
    [self getVerifyCodeNumber];
}

// 获得验证码
- (void)getVerifyCodeNumber {
    [SVProgressHUD showInfoWithStatus:MyNSLocalizedString(@"正在获取验证码...")];

    PublicGetRegisterCodeApi * codeApi = [[PublicGetRegisterCodeApi alloc] initWithDic:@{@"username":self.containerView.phoneView.phoneTextField.text}];
    [codeApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary * codeDic = [request responseJSONObject];
        NSLog(@"code Dic == %@ ",codeDic);
        //        [codeApi analyseResponseObject];

        if ([codeDic[@"errcode"] intValue] == 0) {
            [SVProgressHUD showInfoWithStatus:codeDic[@"errmsg"]];
            [self setVerifyBtnTimer];
            SAVE_OBJECT(codeDic[@"vcode"], @"vcode");
        }else{
            [SVProgressHUD showErrorWithStatus:codeDic[@"errmsg"]];
        }

    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"请求超时"];
    }];
}

- (void)didClickRegisterButton
{
    
    if (![self.containerView.phoneView.phoneTextField.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请输入正确的手机号码...")];
        return;
    }
    
    if (![self.containerView.passwordView.phoneTextField.text isRegexPassword]) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"请输入符合规定的密码")];
        return;
    }
    
    if (self.containerView.verifyView.verifyTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"亲，还未输入验证码...")];
        return;
    }
    
    if (self.containerView.verifyView.verifyTextField.text.length < 6 || self.containerView.verifyView.verifyTextField.text.length > 6) {
        [SVProgressHUD showErrorWithStatus:MyNSLocalizedString(@"亲，请输入6位验证码...")];
        return;
    }
    
    [self registerActionStart];
}



- (void)didClickProtocolButton
{
    WebViewController *vc = [[WebViewController alloc] init];
    vc.webViewType = UserAgreement;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)backBtnAction:(id)sender {
    
    NSArray * viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1] == self) {
            [self.navigationController popViewControllerAnimated:YES];  //push方式
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];   //present方式
    }
}

#pragma mark - 事件处理
// 设置定时器
- (void)setVerifyBtnTimer {
    __block int code_out = 60;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (code_out <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_containerView.verifyView.verifyButton setTitle:MyNSLocalizedString(@"获取验证码") forState:0];
                [_containerView.verifyView.verifyButton setTitle:MyNSLocalizedString(@"60秒后获取") forState:UIControlStateDisabled];
                _containerView.verifyView.verifyButton.enabled = YES;
                code_out = 60;
            });
        } else {
            _containerView.verifyView.verifyButton.enabled = NO;
            NSString * time = [NSString stringWithFormat:@"%d %@",code_out,MyNSLocalizedString(@"秒后获取")];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_containerView.verifyView.verifyButton setTitle:time forState:UIControlStateDisabled];
            });
            code_out -- ;
        }
    });
    dispatch_resume(timer);
}

// 开始注册
- (void)registerActionStart
{
    PublicRegisterApi * registerApi = [[PublicRegisterApi alloc] initWithDic:@{@"username":self.containerView.phoneView.phoneTextField.text,@"password":self.containerView.passwordView.phoneTextField.text,@"vcode":self.containerView.verifyView.verifyTextField.text}];
    [registerApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary * codeDic = [request responseJSONObject];
        if ([codeDic[@"errcode"] intValue] == 0) {
            [SVProgressHUD showSuccessWithStatus:codeDic[@"errmsg"]];

            [NSThread sleepForTimeInterval:0.5];
            [self backBtnAction:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:codeDic[@"errmsg"]];
        }
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showInfoWithStatus:@"请求超时"];
    }];
}

#pragma mark - 代理


#pragma mark - 通知处理

#pragma mark - 初始化
- (RegisterView *)containerView
{
    if(!_containerView)
    {
        UIView *superView = self.view;
        _containerView = [[RegisterView alloc]init];
        [superView addSubview:_containerView];
        [_containerView.verifyView.verifyButton addTarget:self action:@selector(getVerifyCode) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.protocolButton addTarget:self action:@selector(didClickProtocolButton) forControlEvents:UIControlEventTouchUpInside];
        [_containerView.registerButton addTarget:self action:@selector(didClickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _containerView;
}

- (void)setNavigationStyle
{

    [self setNavigationTitle:MyNSLocalizedString(@"注册") titleColor:[UIColor whiteColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"F06161"];
}

- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.equalTo(superView);
    }];
}

@end
